var express = require('express');
const Result = require('../lib/Result');
const isRule = require('../util/isRule');
const Category = require('../db/models/category/category');
const Goods = require('../db/models/goods/goods');
var router = express.Router();
/**
 * 商品分类列表,71,14,6
 */
router.get("",(req,res)=>{
    let token = req.auth
    if (isRule(token.rule, [71, 14, 6], res, token.super)) {
        Category.getCategoryAll().then(value=>{
            res.json(Result.success(value))
        })
    }
})
/**
 * 分类关联产品列表,71,14,6
 */
router.get("/:id/goods/:page",(req,res)=>{
    let token = req.auth
    let limit=Number(req.query.limit)
    let page=Number(req.params.page)
    if (isRule(token.rule, [71, 14, 6], res, token.super)) {
        Goods.getGoodsAsCategory(req.params.id,limit,page).then(value=>{
            res.json(Result.success(value))
        })
    }
})
/**
 * 创建分类列表，72，14，6
 */
router.post("",(req,res)=>{
    let token = req.auth
    let name=req.body.name
    let category_id=req.body.category_id
    let img=req.body.img
    if (isRule(token.rule, [72, 14, 6], res, token.super)) {
        if (!name) {
            return res.json(Result.validateFailed())
        }
        Category.addCategory(name,category_id,img).then(value=>{
            res.json(Result.success(value.toJSON()))
        })
    }
})
/**
 * 修改分类列表状态，75，14，6
 */
router.post("/:id/update_status",(req,res)=>{
    let token = req.auth
    let status=req.body.status
    if (isRule(token.rule, [75, 14, 6], res, token.super)) {
        Category.updateStatus(req.params.id,status).then(value=>{
            res.json(Result.success(true))
        })
    }
})
/**
 * 删除分类列表，76，14，6
 */
router.post("/:id/delete",(req,res)=>{
    let token = req.auth
    //如果删除的分类有子分类，在deleteChild不为true时不会进行删除
    let deleteChild=req.body.deleteChild//是否删除子类
    if (isRule(token.rule, [76, 14, 6], res, token.super)) {
        try{
            Category.deleteCategory(req.params.id,deleteChild).then(value=>{
                res.json(Result.success(true))
            })
        }catch(error){
            res.json(Result.validateFailed(error))
        }
    }
})
/**
 * 修改分类列表，74，14，6
 */
router.post("/:id",(req,res)=>{
    let token = req.auth
    let name=req.body.name
    let category_id=req.body.category_id
    if (isRule(token.rule, [74, 14, 6], res, token.super)) {
        Category.addCategory(name,category_id,req.params.id).then(value=>{
            res.json(Result.success(value.toJSON()))
        })
    }
})
module.exports=router